<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--风险分析对象数据-->
      <el-col :span="6" :xs="24">
        <div class="head-container">
          <el-input
            v-model="keyValue"
            placeholder="请输入风险分析对象名称"
            clearable
            prefix-icon="Search"
            style="margin-bottom: 20px"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="targetOptions"
            :props="{ label: 'riskTargetName', child: '' }"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="targetShowRef"
            node-key="riskTargetId"
            :current-node-key="checkNode"
            highlight-current
            default-expand-all
            @node-click="handleNodeClick"
          >
            <template class="custom-tree-node" #default="{ node, data }">
              <div
                style="
                  display: flex;
                  align-items: flex-start;
                  justify-content: space-between;
                  width: 100%;
                "
              >
                <span style="padding-left: 4px">{{ node.label }}</span>
                <span>
                  <el-button
                    link
                    type="primary"
                    icon="Edit"
                    @click="handleTargetUpdate(data)"
                    v-hasPermi="['risk:target:edit']"
                  ></el-button>
                  <el-button
                    link
                    type="primary"
                    icon="Delete"
                    @click="handleTargetDelete(data)"
                    v-hasPermi="['risk:target:remove']"
                  ></el-button>
                </span>
              </div>
            </template>
          </el-tree>
        </div>
        <div class="head-container" style="margin-top: 15px; text-align: center">
          <el-button
            type="primary"
            plain
            icon="Plus"
            @click="handleAdd"
            v-hasPermi="['risk:target:add']"
            >新增</el-button
          >
        </div>
      </el-col>

      <!--风险分析单元数据-->
      <el-col :span="18" :xs="24">
        <el-row :gutter="10" class="mb8 right">
          <el-col :span="24" style="display: flex; justify-content: end">
            <el-button
              type="primary"
              icon="Plus"
              @click="handleUnitAdd"
              v-hasPermi="['risk:unit:add']"
              >新增风险分析单元</el-button
            >
          </el-col>
        </el-row>
        <el-table v-loading="loading" :data="unitShowList">
          <!-- <el-table-column type="selection" width="50" align="center" /> -->
          <!-- <el-table-column label="所属风险分析对象" align="center" key="userId" prop="userId"  /> -->
          <el-table-column
            label="风险分析单元名称"
            align="center"
            key="riskUnitName"
            prop="riskUnitName"
          />
          <el-table-column
            label="责任部门"
            align="center"
            key="hazardDep"
            prop="hazardDep"
          />
          <el-table-column
            label="责任人"
            align="center"
            key="hazardLiablePerson"
            prop="hazardLiablePerson"
          />
          <el-table-column label="二维码" align="center" key="qrCodeUrl" prop="qrCodeUrl">
            <template #default="scope">
              <el-button type="primary" @click="handleCode(scope.row)">查看</el-button>
            </template>
          </el-table-column>
          <el-table-column label="状态" align="center" prop="riskUnitStatus" width="160">
            <template #default="scope">
              <el-switch
                v-model="scope.row.riskUnitStatus"
                active-value="0"
                inactive-value="1"
                disabled
              ></el-switch>
            </template>
          </el-table-column>

          <el-table-column label="创建时间" align="center" prop="createdAt" width="160">
            <template #default="scope">
              <span>{{ parseTime(scope.row.createdAt) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            label="操作"
            align="center"
            width="150"
            class-name="small-padding fixed-width"
          >
            <template #default="scope">
              <el-tooltip content="修改" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleUpdate(scope.row)"
                  v-hasPermi="['risk:unit:edit']"
                ></el-button>
              </el-tooltip>
              <el-tooltip content="删除" placement="top" v-if="scope.row.userId !== 1">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                  v-hasPermi="['risk:unit:remove']"
                ></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>

    <!-- 添加或修改风险分析对象对话框 -->
    <el-dialog :title="titleTarget" v-model="openTarget" width="60%" append-to-body>
      <el-form
        :model="targetForm"
        :rules="targetRules"
        ref="targetRef"
        label-width="80px"
      >
        <el-tabs
          v-model="activeTabName"
          type="card"
          class="demo-tabs"
          @tab-click="handleClick"
        >
          <el-tab-pane label="风险分析对象" name="1">
            <el-row>
              <el-col :span="24">
                <el-form-item
                  label="风险分析对象名称:"
                  label-width="140px"
                  prop="riskTargetName"
                >
                  <el-input
                    v-model="targetForm.riskTargetName"
                    placeholder="请输入风险分析对象名称"
                    maxlength="30"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="危险源等级划分:" label-width="140px">
                  <el-select
                    v-model="targetForm.hazardLevelId"
                    placeholder="请选择危险源等级"
                    prop="hazardLevelId"
                  >
                    <el-option
                      v-for="item in hazardLevelOptions"
                      :key="item.hazardLevelId"
                      :label="item.hazardLevelName"
                      :value="item.hazardLevelId"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col
                :span="24"
                v-if="
                  targetForm.hazardLevelId != 5 && targetForm.hazardLevelId != undefined
                "
              >
                <el-form-item
                  label="风险分析对象编码:"
                  label-width="140px"
                  prop="hazardCode"
                >
                  <el-input
                    v-model="targetForm.hazardCode"
                    placeholder="同“危险化学品登记信息管理系统”一致"
                    maxlength="30"
                  />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="所在部门:" label-width="140px" prop="deptId">
              <el-tree-select
                v-model="targetForm.deptId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择部门"
                check-strictly
              />
            </el-form-item>
          </el-tab-pane>
          <el-tab-pane
            v-if="targetForm.hazardLevelId != 5 && targetForm.hazardLevelId != undefined"
            label="包保责任制"
            name="2"
          >
            <el-card class="box-card">
              <template #header>
                <div class="card-header">
                  <span style="color: #0087ff; font-size: 12px">主要负责人</span>
                </div>
              </template>
              <div class="body">
                <el-row :gutter="12">
                  <el-col :span="8">
                    <el-form-item label="主要负责人:" label-width="140px" required>
                      <el-select
                        v-model="targetForm.riskTargetResponsibility.chargeUserId"
                        clearable
                        filterable
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="dict in liablePersonOptions"
                          :key="dict.id"
                          :label="dict.label"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="责任人职责:" label-width="140px" required>
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="targetForm.riskTargetResponsibility.chargeUserDesc"
                    placeholder="请输入责任人岗位"
                  />
                </el-form-item>
              </div>
            </el-card>
            <el-card class="box-card" style="margin-top: 12px">
              <template #header>
                <div class="card-header">
                  <span style="color: #0087ff; font-size: 12px">技术负责人</span>
                </div>
              </template>
              <div class="body">
                <el-row :gutter="12">
                  <el-col :span="8">
                    <el-form-item label="技术负责人:" label-width="140px" required>
                      <el-select
                        v-model="targetForm.riskTargetResponsibility.skillUserId"
                        clearable
                        filterable
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="dict in liablePersonOptions"
                          :key="dict.id"
                          :label="dict.label"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="责任人职责:" label-width="140px" required>
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="targetForm.riskTargetResponsibility.skillUserDesc"
                    placeholder="请输入责任人岗位"
                  />
                </el-form-item>
              </div>
            </el-card>
            <el-card class="box-card" style="margin-top: 12px">
              <template #header>
                <div class="card-header">
                  <span style="color: #0087ff; font-size: 12px">操作负责人</span>
                </div>
              </template>
              <div class="body">
                <el-row :gutter="12">
                  <el-col :span="12">
                    <el-form-item label="操作负责人:" label-width="140px" required>
                      <el-select
                        v-model="targetForm.riskTargetResponsibility.operateUserId"
                        clearable
                        filterable
                        placeholder="请选择"
                      >
                        <el-option
                          v-for="dict in liablePersonOptions"
                          :key="dict.id"
                          :label="dict.label"
                          :value="dict.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-form-item label="责任人职责:" label-width="140px" required>
                  <el-input
                    type="textarea"
                    :rows="3"
                    v-model="targetForm.riskTargetResponsibility.operateUserDesc"
                    placeholder="请输入责任人职责"
                  />
                </el-form-item>
              </div>
            </el-card>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="dialog-footer" v-if="showSubmit">
          <el-button
            type="primary"
            v-if="
              targetForm.hazardLevelId != 5 &&
              targetForm.hazardLevelId != undefined &&
              activeTabName == '2'
            "
            @click="nextTab('up')"
            >上一步</el-button
          >
          <el-button type="primary" @click="submitTargetForm">确 定</el-button>
          <el-button @click="cancelTarget">取 消</el-button>
        </div>
        <div class="dialog-footer" v-else>
          <el-button type="primary" @click="nextTab('down')">下一步</el-button>
          <el-button @click="cancelTarget">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--添加或修改风险分析单元对话框-->
    <el-dialog :title="titleUnit" v-model="openUnit" width="600px" append-to-body>
      <el-form :model="unitForm" :rules="rules" ref="UnitRef" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="所属风险分析对象:"
              label-width="140px"
              prop="riskTargetId"
            >
              <el-select
                v-model="unitForm.riskTargetId"
                disabled
                placeholder="请选择所属风险分析对象"
              >
                <el-option
                  v-for="item in targetOptions"
                  :key="item.riskTargetId"
                  :label="item.riskTargetName"
                  :value="item.riskTargetId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="风险分析单元名称:"
              label-width="140px"
              prop="riskUnitName"
            >
              <el-input
                v-model="unitForm.riskUnitName"
                placeholder="同“危险化学品登记信息管理系统”一致"
                maxlength="30"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="责任部门:" label-width="140px" prop="hazardDepId">
              <el-tree-select
                v-model="unitForm.hazardDepId"
                :data="deptOptions"
                :props="{ value: 'id', label: 'label', children: 'children' }"
                value-key="id"
                placeholder="请选择责任部门"
                check-strictly
                @current-change="checkedDept"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="责任人:" label-width="140px" prop="hazardLiableUserId">
              <el-select
                v-model="unitForm.hazardLiableUserId"
                @change="checkedUser"
                placeholder="请选择责任人"
              >
                <el-option
                  v-for="item in userOptions"
                  :key="item.userId"
                  :label="item.nickName"
                  :value="item.userId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitUnitForm">确 定</el-button>
          <el-button @click="cancelUnit">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!--二维码预览对话框-->
    <el-dialog v-model="dialogVisible">
      <img w-full :src="codeUrl" alt="Preview Image" />
    </el-dialog>
  </div>
</template>
<script setup name="Unit">
import {
  listTarget,
  addTarget,
  deleteTarget,
  updateTarget,
  getTargetInfo,
} from "@/api/prevent/risk/target";
import {
  listUnit,
  addUnit,
  deleteUnit,
  updateUnit,
  getUnitInfo,
} from "@/api/prevent/risk/unit";
import { listHazardLevel } from "@/api/prevent/setting/setting";
import { deptTreeSelect, userTreeSelect } from "@/api/system/user";
import { listDutyUser } from "@/api/prevent/hidden/dutyUser";
const { proxy } = getCurrentInstance();
const openTarget = ref(false);
const openUnit = ref(false);
const loading = ref(true);
const keyValue = ref("");
const titleTarget = ref("");
const titleUnit = ref("");
const unitList = ref(undefined);
const unitShowList = ref([]);
const hazardLevelOptions = ref(undefined);
const targetOptions = ref(undefined);
const checkNode = ref("");
const checkNodeHazardCode = ref("");
const checkNodeHazardLevelId = ref(undefined);
const deptOptions = ref([]);
const userOptions = ref([]);
const activeTabName = ref("1");
const showSubmit = ref(true);
const liablePersonOptions = ref([]);
const titleDownTime = ref("");
const dialogVisible = ref(false);
const codeUrl = ref("");
const openDownTime = ref(false);

const data = reactive({
  targetForm: {
    riskTargetResponsibility: {},
  },
  unitForm: {},

  queryParams: {
    current: 1,
    size: 10,
  },
  rules: {
    riskTargetId: [{ required: true, message: "风险分析对象必须选择", trigger: "blur" }],
    riskUnitName: [
      { required: true, message: "风险分析单元名称必须填写", trigger: "blur" },
    ],
    hazardDepId: [{ required: true, message: "责任部门必须选择", trigger: "blur" }],
    hazardLiableUserId: [{ required: true, message: "责任人必须选择", trigger: "blur" }],
  },
  targetRules: {
    riskTargetName: [
      { required: true, message: "风险分析对象名称不能为空", trigger: "blur" },
      { min: 2, max: 20, message: "长度必须介于 2 和 20 之间", trigger: "blur" },
    ],
    hazardCode: [
      {
        required: true,
        message: "编码不能为空，请保持与危险化学品登记信息管理系统一致",
        trigger: "blur",
      },
    ],
    deptId: [{ required: true, message: "危险源所在部门必须选择", trigger: "blur" }],
    hazardLevelId: [{ required: true, message: "危险源等级必须选择", trigger: "blur" }],
    chargeUserId: [{ required: true, message: "主要负责人必须选择", trigger: "blur" }],
    chargeUserDesc: [
      { required: true, message: "主要责任人职责必须填写！", trigger: "blur" },
    ],
    skillUserId: [{ required: true, message: "技术负责人必须选择", trigger: "blur" }],
    skillUserDesc: [
      { required: true, message: "技术责任人职责必须填写！", trigger: "blur" },
    ],
    operateUserId: [{ required: true, message: "操作负责人必须选择", trigger: "blur" }],
    operateUserDesc: [
      { required: true, message: "操作责任人职责必须填写！", trigger: "blur" },
    ],
  },
});

const { targetForm, unitForm, rules, targetRules } = toRefs(data);

/** 处理二维码图片呈现 */
function handleCode(row) {
  dialogVisible.value = true;
  codeUrl.value = row.qrCodeUrl;
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}

/** 根据名称筛选风险分析对象 */
watch(keyValue, (val) => {
  proxy.$refs["targetShowRef"].filter(val);
});

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.riskTargetName.indexOf(value) !== -1;
};

/** 处理新增风险切换 */
const handleClick = (tab, event) => {
  if (tab.props.name == "2") {
    showSubmit.value = true;
  } else {
    showSubmit.value = false;
  }
};
/** 处理重大危险源风险分析对象的下一步包保责任制 */
function nextTab(flag) {
  if (activeTabName.value == "1") {
    activeTabName.value = "2";
    showSubmit.value = true;
  } else {
    if (flag == "up") {
      activeTabName.value = "1";
      showSubmit.value = false;
    }
  }
}

/** 监听重大危险源等级 */
watch(
  () => targetForm.value.hazardLevelId,
  (newVal, oldVal) => {
    if (newVal == 5 && activeTabName.value == "1") {
      showSubmit.value = true;
    } else {
      showSubmit.value = false;
    }
  }
);

/** 节点单击事件 */
function handleNodeClick(data) {
  checkNode.value = data.riskTargetId;
  checkNodeHazardCode.value = data.hazardCode;
  checkNodeHazardLevelId.value = data.hazardLevelId;
  changeUnitShow();
}
/** 查询风险分析对象下拉树结构 */
function getTargetList() {
  listTarget().then((response) => {
    targetOptions.value = response.data;
    //console.log(response.data[0]);
    if (response.data.length > 0) {
      checkNode.value = response.data[0].riskTargetId;
      checkNodeHazardCode.value = response.data[0].hazardCode;
      checkNodeHazardLevelId.value = response.data[0].hazardLevelId;
    }
  });
  //console.log("查询风险分析对象下拉树结构");
}

/** 查询危险源等级下拉树结构 */
function getHazardLevel() {
  listHazardLevel().then((response) => {
    hazardLevelOptions.value = response.data;
  });
}

/** 风险分析对象表单重置 */
function resetTarget() {
  targetForm.value = {
    riskTargetName: undefined,
    hazardCode: undefined,
    hazardLevelId: undefined,
    del_flag: "0",
    riskTargetResponsibility: {},
  };
  proxy.resetForm("targetRef");
  showSubmit.value = true;
  activeTabName.value = "1";
}

/** 新增风险分析对象按钮操作 */
function handleAdd() {
  resetTarget();
  openTarget.value = true;
  titleTarget.value = "添加风险分析对象";
}

/** 提交风险分析对象表单按钮 */
function submitTargetForm() {
  proxy.$refs["targetRef"].validate((valid) => {
    if (valid) {
      if (targetForm.value.riskTargetId != undefined) {
        updateTarget(targetForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改风险分析对象成功");
          openTarget.value = false;
          getTargetList();
        });
      } else {
        addTarget(targetForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增风险分析对象成功");
          openTarget.value = false;
          getTargetList();
        });
      }
    }
  });
}
/**处理风险分析对象更新操作 */
function handleTargetUpdate(row) {
  resetTarget();
  getTargetInfo(row.riskTargetId).then((response) => {
    targetForm.value = response.data;
    openTarget.value = true;
    titleTarget.value = "更新风险分析对象";
  });
}
/**处理风险分析对象删除操作 */
function handleTargetDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.riskTargetName + '"的数据项?')
    .then(function () {
      return deleteTarget(row.riskTargetId);
    })
    .then(() => {
      getTargetList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 取消按钮 */
function cancelTarget() {
  openTarget.value = false;
  resetTarget();
}

/** --------------风险分析单元处理------------------ */

/** 更新风险分析单元呈现数据 */
function changeUnitShow() {
  unitShowList.value = [];
  unitList.value.filter((item, i, arr) => {
    if (checkNode.value == "" || checkNode.value == null) {
      setTimeout(() => {
        if (item.riskTargetId == checkNode.value) {
          unitShowList.value.push(item);
        }
      }, 500);
    } else {
      if (item.riskTargetId == checkNode.value) {
        unitShowList.value.push(item);
      }
    }
  });
}

/** 风险分析对象表单重置 */
function resetUnit() {
  unitForm.value = {
    riskTargetId: checkNode.value,
    hazardCode: checkNodeHazardCode.value,
    hazardDep: undefined,
    hazardLiablePerson: undefined,
    hazardLevelId: checkNodeHazardLevelId.value,
    delFlag: "0",
  };
  proxy.resetForm("UnitRef");
}

/** 获取风险分析单元列表 */
function getUnitList() {
  loading.value = true;
  listUnit().then((response) => {
    unitList.value = response.data;
    changeUnitShow();
  });
  loading.value = false;
}
/** 添加风险分析单元 */
function handleUnitAdd() {
  resetUnit();
  openUnit.value = true;
  titleUnit.value = "添加风险分析单元";
}

/** 取消添加风险分析单元按钮 */
function cancelUnit() {
  openUnit.value = false;
  resetUnit();
}

/** 选择中了部门选择用户 */
function checkedDept(check, node) {
  unitForm.value.hazardDep = check.label;
  getUserForSelect(check.id);
}
/** 获取责任人选择项 */
function getUserForSelect(deptId) {
  userTreeSelect(deptId).then((response) => {
    userOptions.value = response.data;
  });
}

/** 选择用户 */
function checkedUser(check) {
  userOptions.value.filter((item, i, arr) => {
    if (item.userId == check) {
      unitForm.value.hazardLiablePerson = item.nickName;
    }
  });
}

/** 提交风险分析单元表单按钮 */
function submitUnitForm() {
  proxy.$refs["UnitRef"].validate((valid) => {
    if (valid) {
      if (unitForm.value.riskUnitId != undefined) {
        updateUnit(unitForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改风险分析单元成功");
          openUnit.value = false;
          getUnitList();
        });
      } else {
        addUnit(unitForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增风险分析单元成功");
          openUnit.value = false;
          getUnitList();
        });
      }
    }
  });
}

/** 处理风险分析单元删除操作  */
function handleDelete(row) {
  proxy.$modal
    .confirm('是否确认删除名称为"' + row.riskUnitName + '"的数据项?')
    .then(function () {
      return deleteUnit(row.riskUnitId);
    })
    .then(() => {
      getUnitList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
}
/** 处理风险分析单元更新操作  */
function handleUpdate(row) {
  resetUnit();
  getUnitInfo(row.riskUnitId).then((response) => {
    getUserForSelect(response.data.hazardDepId);
    unitForm.value = response.data;
    // console.log("更新风险分析单元");
    // console.log(unitForm.value);
    openUnit.value = true;
    titleUnit.value = "修改风险分析单元";
    unitForm.value.hazardDepId = parseInt(response.data.hazardDepId);
    unitForm.value.hazardLiableUserId = parseInt(response.data.hazardLiableUserId);
  });
}
/** 获取责任人数据列表 */
async function getCheckUserList() {
  listDutyUser().then((response) => {
    liablePersonOptions.value = response.data;
  });
}

/**初始化调用 */
getCheckUserList();
getHazardLevel();
getTargetList();
getDeptTree();
getUnitList();
</script>
<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.el-tree :deep(.el-tree-node__content) {
  height: 38px;
}
</style>
